package com.mc.moring.main.loan

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gyf.immersionbar.ImmersionBar
import com.mc.moring.BafBase.BAFBaseActivity
import com.mc.moring.R
import com.mc.moring.app.LogUtils
import com.mc.moring.base.HttpCallback
import com.mc.moring.bean.AppConfigBean
import com.mc.moring.bean.AppConfigBeanData
import com.mc.moring.bean.DataBean
import com.mc.moring.bean.LastLoanDetailBean
import com.mc.moring.bean.LoanInfoVo
import com.mc.moring.bean.MPayLoanChildBean
import com.mc.moring.bean.SingleSelectBean
import com.mc.moring.bean.WebLinkBean
import com.mc.moring.main.WebViewActivity
import com.mc.moring.main.modle.LoanModle
import com.mc.moring.main.modle.MianModle
import com.mc.moring.main.modle.PermisosModle.Companion.instant
import com.mc.moring.util.GsonUtils
import com.mc.moring.util.PointMgr
import com.mc.moring.util.SharePreUtil
import com.mc.moring.util.StringUtils
import com.mc.moring.util.TimeUtils
import com.mc.moring.widge.NumberView
import com.mc.moring.widge.SingleSelectMomenyDialogView
import com.mc.moring.widge.VerticalDashedLineView
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.Date


/**
 *
 * @ProjectName:    Monicash
 * @Package:        com.moring.moring.main.loan
 * @ClassName:      MPayLoanActivity
 * @Author:         ANWEN
 * @CreateDate:     2024/1/14 22:39
 * @UpdateUser:
 * @UpdateDate:     2024/1/14 22:39
 * @UpdateRemark:
 * @Version:
 */
class MPayLoanActivity : BAFBaseActivity<MPayLoanActivity>() {

    private val recycler_view by lazy { findViewById<RecyclerView>(R.id.recycler_view) }
    private val abBackIBtn by lazy { findViewById<View>(R.id.abBackIBtn) }
    private val tv_money by lazy { findViewById<NumberView>(R.id.tv_money) }
    private val tv_repay_date by lazy { findViewById<TextView>(R.id.tv_repay_date) }
    private val tv_total_money by lazy { findViewById<NumberView>(R.id.tv_total_money) }
    private val tv_sub by lazy { findViewById<TextView>(R.id.tv_sub) }
    private val iv_edit by lazy { findViewById<ImageView>(R.id.iv_edit) }
    private val rl_tips by lazy { findViewById<RelativeLayout>(R.id.rl_tips) }
    private val iv_close_tip by lazy { findViewById<ImageView>(R.id.iv_close_tip) }
    private val loadModel by lazy { LoanModle() }
    private val mainModel by lazy { MianModle() }
    private val tv_bottom_tip by lazy{findViewById<TextView>(R.id.tv_bottom_tip)}

    private var paymentId : String? = null
    private var phone: String? = ""

    override fun initParameter(bundle: Bundle?) {
    }

    override fun initLayout(): Int {
        return R.layout.activity_m_pay_load
    }

    override fun initImmersionBar() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun afterInjectView() {
        LogUtils.logE("pay loan page")
        PointMgr.sendEvent("cl_video_13_upload_yes")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_video_13_upload_yes")
        //resetTipsStates
        phone = intent?.getStringExtra("phone")
        SharePreUtil.saveStringData("loan_tip", "justShowTip1:$phone")
        paymentId = intent?.getStringExtra("paymentId")
        paymentId?.let { getLoanSummaryByPaymentId(it) }
        showRecyclerView();
        abBackIBtn.setOnClickListener {
            finish()
        }
        val typefaceName = Typeface.createFromAsset(assets, "Poppins-SemiBold.ttf")
        tv_bottom_tip.typeface = typefaceName
        tv_total_money.typeface = typefaceName
        tv_sub.setOnClickListener {
            PointMgr.sendEvent("cl_video_15_upload_yes")
            Log.e("PointMgr.INSTANCE.sendEvent", "cl_video_15_upload_yes")
            if (TextUtils.equals(tv_money.text.toString(), "0")) {
                return@setOnClickListener;
            }
            getZiLiPageWebLinkConfig()
        }

        securitygetApplicationConfig()

        iv_edit.setOnClickListener {
            showSelectMoney(it);
        }
        iv_close_tip.setOnClickListener {
            rl_tips.visibility = View.GONE
            iv_close_tip.visibility = View.GONE
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun hideLoading() {
    }

    override fun showLoading(msg: String?) {
    }

    fun convertThousandSeparatorToDouble(formattedNumber: String, pattern: String = "#,###.##"): Double? {
        require(!formattedNumber.isNullOrBlank()) { "Formatted number cannot be null or empty" }

        val decimalFormat = DecimalFormat(pattern)

        try {
            val parsedNumber = decimalFormat.parse(formattedNumber)
            return parsedNumber?.toDouble()
        } catch (e: NumberFormatException) {
            e.printStackTrace()
            return 0.toDouble()
        }
    }

    private fun showSelectMoney(view: View){
        var calLoanAmount = 0
//        val showMoney = convertThousandSeparatorToDouble(tv_money.text.toString())
        val showMoney = tv_money.getAmount()
        var showMoneyValue = -1
        if (appConfigBeanData != null) {
            try {
                calLoanAmount = appConfigBeanData!!.calLoanAmount.toInt()
                showMoneyValue = showMoney!!.toInt()
            } catch (e: java.lang.Exception) {
                e.printStackTrace()
            }
        }

        if (dataBean == null) {
            return
        }

        var minApplyAmount = 0
        var creditLine = 0
        for (i in mLoanInfoVoList.indices) {
            val item: LoanInfoVo = mLoanInfoVoList[i]
            val status: Int = item.status
            when (status) {
                2002, 3001, 3002 -> {
//                    if (minApplyAmount == 0) {
//                        minApplyAmount = item.currentPeriodTotalSurplusAmount.toInt()
//                    }
                    creditLine = creditLine + item.currentPeriodTotalSurplusAmount.toInt()
                }
            }
        }

        var list: MutableList<SingleSelectBean> = ArrayList()
        var moneyList = mutableListOf<Int>()
        var showIndex = 0
        val valueList: MutableList<String> = java.util.ArrayList()
        if (calLoanAmount == 0) {
            valueList.add("$$creditLine")
            list.add(SingleSelectBean("$${StringUtils.formatNumberWithCommas(creditLine.toString())}", "${creditLine}"))
        } else {
            val count = ((creditLine - minApplyAmount) / calLoanAmount).toInt()
            for (i in 0 until count) {
                val money = (creditLine - calLoanAmount * i).toInt()
                valueList.add(0,"$$money")
                list.add(0,SingleSelectBean("$${StringUtils.formatNumberWithCommas(money.toString())}", "${money}"))
                moneyList.add(0,money)
            }
            list = list.reversed().toMutableList()
            moneyList = moneyList .reversed().toMutableList()
            moneyList.forEachIndexed { index, money ->
                if (showMoneyValue == money.toInt()) {
                    showIndex = index
                }
            }
            val closestIndex = findClosestIndex(showMoneyValue, moneyList)

            if (closestIndex != null) {
                showIndex = closestIndex
            }

            if (count == 0) {
                valueList.add("$$creditLine")
                list.add(SingleSelectBean("$$creditLine", "${creditLine}"))
            }
        }
        var selectPop = SingleSelectMomenyDialogView(this@MPayLoanActivity, view, "¿Cuánto quieres devolver?");
        selectPop.showSingleSelectDialog(this@MPayLoanActivity, list, showIndex)
        selectPop.setSingleSelectListener(object :
            SingleSelectMomenyDialogView.SingleSelectListener {
            override fun checked(s: SingleSelectBean?) {
                if (!s!!.code.isNullOrEmpty()) {
//                    val moneyText = StringUtils.formatNumberWithCommas(s!!.code)
//                    tv_money.setText(moneyText)
                    Log.e("----money1",s!!.code.toFloat().toString())
                    tv_money.setAmount(s!!.code.toFloat(), true)
                    tv_total_money.setAmount(s!!.code.toFloat(), false)

//                    tv_total_money.setText("$$moneyText")
                    for (index in 0 until adapter!!.datas.size) {
                        var item = adapter!!.datas.get(index)
                        item.isSelector = false;
                    }
                    adapter?.notifyDataSetChanged()
                }
            }
        })

    }

    fun findClosestIndex(target: Int, numbers: List<Int>): Int? {
        if (numbers.isEmpty()) {
            return null
        }

        var closestNumber = numbers[0]
        var minDifference = Math.abs(target - closestNumber)
        var closestIndex = 0

        for ((index, number) in numbers.withIndex()) {
            val difference = Math.abs(target - number)
            if (difference < minDifference) {
                minDifference = difference
                closestNumber = number
                closestIndex = index
            }
        }

        return closestIndex
    }

    var mLoanInfoVoList: MutableList<LoanInfoVo> = ArrayList()
    private var adapter: MPayLoanAdapter? = null
    private fun showRecyclerView() {
        recycler_view.layoutManager = LinearLayoutManager(this)
        if (adapter == null) {
            adapter = MPayLoanAdapter(this)
        }
        adapter?.datas = mLoanInfoVoList;
        recycler_view.adapter = adapter
        adapter?.itemClick = object : MPayLoanAdapter.onItemClickListener {
            override fun onItemClick(view: View, position: Int, isSelect: Boolean) {
                showSelectInfo(position, isSelect)
            }
        }

        adapter?.showClick = object : MPayLoanAdapter.onItemClickListener {
            override fun onItemClick(view: View, position: Int, isSelect: Boolean) {
                showInfo()
            }
        }
    }

    private fun showSelectInfo() {
        var total = 0
        var minTotal = 0;
        for (index in 0 until mLoanInfoVoList.size) {
            var item = mLoanInfoVoList.get(index)
            var status = item.status
            LogUtils.logE("kelvin--showSelectInfo--currentPeriodTotalSurplusAmount:$item.currentPeriodTotalSurplusAmount")
            if (minTotal == 0 && (status == 2002 || status == 3001 || status == 3002)){
                minTotal = item.currentPeriodTotalSurplusAmount.toInt();
            }
            if (item.isSelector) {
                total += item.currentPeriodTotalSurplusAmount.toInt()
            }
        }
        if (total == 0){
            total = minTotal;
        }
//        val totalTx = StringUtils.formatNumberWithCommas(total.toString())
//        tv_money.setText(totalTx)
        Log.e("----money2",total.toFloat().toString())
        tv_money.setAmount(total.toFloat(), true)
//        tv_total_money.setText("$${totalTx}")
        tv_total_money.setAmount(total.toFloat(), false)

        try {
            if (TextUtils.equals(appConfigBeanData!!.partRepaySwitch, "1")) {
                var minAmout:String = appConfigBeanData!!.minRepayAmount
                if (minAmout == ""){
                    minAmout = "1000"
                }
//                if (dataBean!!.totalSurplusAmount.toDouble() > minAmout.toDouble()) {
                if (dataBean!!.totalSurplusAmount.toDouble() > 1000) {
                    iv_edit.setVisibility(View.VISIBLE)
                } else {
                    iv_edit.setVisibility(View.GONE)
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }

    }

    private fun showSelectInfo(position: Int, isSelect: Boolean) {
        var total = 0
        var minTotal = 0;

        val today = Date()
        val formatter = SimpleDateFormat("yyyyMMdd")
        val formattedDate: String = formatter.format(today)
        Log.e("----today",formattedDate)
        for (index in 0 until mLoanInfoVoList.size) {
            var item = mLoanInfoVoList.get(index)
            Log.e("----min",GsonUtils.getGson().toJson(item))



            var status = item.status
            var date = item.dueDate.replace("-","")
            var setThisMoney = false
            if ( formattedDate.toInt() >= date.toInt() ){
                setThisMoney = true
            }

            if (
                setThisMoney && (status == 2002 || status == 3001 || status == 3002)
                ){
                minTotal += item.currentPeriodTotalSurplusAmount.toInt()
            }
            LogUtils.logE(" ---mpayload index:$index, position:$position")
            if (isSelect) {
                item.isSelector = index <= position
            } else {
                item.isSelector = index < position
            }
            if (item.isSelector) {
                total += item.currentPeriodTotalSurplusAmount.toInt()
                Log.e("----total",total.toString())
            }
        }
        if ( minTotal == 0 ){
            minTotal = mLoanInfoVoList.get(0).currentPeriodTotalSurplusAmount.toInt()
        }
        if (total == 0){
            total = minTotal;
        }
//        val totalTx = StringUtils.formatNumberWithCommas(total.toString())
//        tv_money.setText(totalTx)
        Log.e("----money3",total.toFloat().toString())
        tv_money.setAmount(total.toFloat(), true)
//        tv_total_money.setText("$${totalTx}")
        tv_total_money.setAmount(total.toFloat(), false)
        adapter?.notifyDataSetChanged()
    }

    private fun showInfo() {
        adapter?.notifyDataSetChanged()
    }

    private fun getLoanSummaryByPaymentId(paymentId: String) {
        if (TextUtils.isEmpty(paymentId)) {
            return
        }

        val params: MutableMap<String, String> = HashMap()
        params["paymentId"] = paymentId
//        showMyLoading()
        loadModel.getLoanSummaryByPaymentId(params, object : HttpCallback{
            override fun onSuccess(data: String) {
                try {
                    var bean: LastLoanDetailBean =
                        GsonUtils.getGson().fromJson(data, LastLoanDetailBean::class.java)
                    if (bean.code == "0000") {
                        var loanInfoVoList = bean.data.loanInfoVoList
                        LogUtils.logE(" --pay-Summary-loanInfoVoList: ${GsonUtils.getGson().toJson(loanInfoVoList)}")
                        LogUtils.logE(" ---pay-Summary- loanInfoVoList.size: ${loanInfoVoList.size}")
                        dataBean = bean.data
                        if (loanInfoVoList != null) {
                            mLoanInfoVoList.addAll(loanInfoVoList)
                            showLoanInfoVoList(loanInfoVoList)
                        }
                        runOnUiThread {
                            tv_repay_date.setText("Fecha limite de pago ${TimeUtils.date2FormatDate(dataBean?.dueDate)}")
                            if (dataBean!!.overDueDays > 0) {
                                tv_repay_date.setTextColor(Color.parseColor("#FF3737"))
                            }
                            showSelectInfo()
                            adapter?.notifyDataSetChanged()
                        }
                    } else {
                        finish()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
                finish()
            }

        })





    }


    var dataBean: DataBean? = null
    private fun loangetLastUnpaidOffLoan() {
        val params: MutableMap<String, String> = java.util.HashMap()
//        showMyLoading()
        loadModel.loangetLastUnpaidOffLoan(params, object : HttpCallback {
            @SuppressLint("SetTextI18n")
            override fun onSuccess(data: String) {
                try {
                    mLoanInfoVoList.clear()
                    var bean: LastLoanDetailBean =
                        GsonUtils.getGson().fromJson(data, LastLoanDetailBean::class.java)
                    if (bean != null) {
                        var loanInfoVoList = bean.data.loanInfoVoList
                        LogUtils.logE(" --pay--loanInfoVoList: ${GsonUtils.getGson().toJson(loanInfoVoList)}")
                        LogUtils.logE(" ---pay-- loanInfoVoList.size: ${loanInfoVoList.size}")
                        dataBean = bean.data
                        if (loanInfoVoList != null) {
                            runOnUiThread {
                                tv_repay_date.setText("Fecha limite de pago ${TimeUtils.date2FormatDate(loanInfoVoList[0].dueDate)}")
                            }
                            mLoanInfoVoList.addAll(loanInfoVoList)
                            showLoanInfoVoList(loanInfoVoList)
                        }
                    }
                    runOnUiThread {
                        showSelectInfo()
                        adapter?.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }

        })
    }

    var lastLoanInfoVo: LoanInfoVo? = null
    private fun showLoanInfoVoList(loanInfoVoList: List<LoanInfoVo>) {
        if (loanInfoVoList == null){
            return;
        }
        runOnUiThread {
            var index = dataBean!!.currPaymentIndex -1;
            if (index >= 0){
                showSelectInfo(index, true)
            }
            lastLoanInfoVo = null
            for (index in 0..loanInfoVoList.size - 1){
                if (lastLoanInfoVo != null){
                    break
                }
                var item = loanInfoVoList.get(index)
                when(item.status){
                    2002, 3001, 3002, 3003->{
                        lastLoanInfoVo = item;
                        lastLoanInfoVo?.isSelector = true;
                    }
                }
            }
        }
    }

    fun getZiLiPageWebLinkConfig() {

        val params: MutableMap<String, String> = java.util.HashMap()
//        showMyLoading()
        instant.getZiLiPageWebLinkConfig(params, object : HttpCallback {
            override fun onSuccess(data: String) {
                try {
                    var webLinkBean = GsonUtils.getGson().fromJson(data, WebLinkBean::class.java)
                    if (webLinkBean != null && webLinkBean.data != null) {
                        PointMgr.sendEvent("cl_video_21_upload_yes")
                        Log.e("PointMgr.INSTANCE.sendEvent", "cl_video_21_upload_yes")
                        var intent = Intent(this@MPayLoanActivity, WebViewActivity::class.java)
                        var isOver = if (dataBean!!.isOver()) 1 else 0
                        val appTime = TimeUtils.dateToStamp(dataBean!!.dueDate)

                        var url =
                            "${webLinkBean.data.repayMethod}?amount=${tv_money.getAmount()}&isOver=$isOver&appTime=$appTime&custId=${lastLoanInfoVo!!.customerId}&paymentId=${dataBean!!.paymentId}&overDueDays=${dataBean!!.overDueDays}"

                        LogUtils.logE("Mpay webLinkUrl: $url")

                        intent.putExtra("url", url)
                        startActivity(intent)

                        finish()
                    }
                } catch (e: java.lang.Exception) {
                    e.printStackTrace()
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
                LogUtils.logE("fail e: $e")
//                hideMyLoading()
            }
        })
    }

    var appConfigBeanData: AppConfigBeanData? = null
    private fun securitygetApplicationConfig(){
        var params: HashMap<String, String> = HashMap()
//        showMyLoading()
        mainModel?.securitygetApplicationConfig(params, object : HttpCallback{
            override fun onSuccess(data: String) {
                var appConfigBean: AppConfigBean = GsonUtils.getGson().fromJson(data, AppConfigBean::class.java);
                if (appConfigBean != null){
                    appConfigBeanData = appConfigBean?.data
                }
//                hideMyLoading()
            }

            override fun onFaill(e: String) {
//                hideMyLoading()
            }

        })
    }

    class MPayLoanAdapter(context: Context?) : RecyclerView.Adapter<MPayLoanActivity.ViewHolder>() {

        var datas: MutableList<LoanInfoVo> = ArrayList()


        var mContext: Context? = context;
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val itemView: View = LayoutInflater.from(mContext)
                .inflate(R.layout.item_m_pay_loan, parent, false)
            return ViewHolder(itemView)
        }

        override fun getItemCount(): Int {
            return datas.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            if ((position + 1) < 10) {
                holder.tv_index.setText("0"+"${position + 1}")
            } else {
                holder.tv_index.setText("${position + 1}")
            }
            var item = datas.get(position);
            var map = item.fieldsMap;
            var myData = GsonUtils.getGson().toJson(item)
            Log.e("===myData", myData)
            Log.e("===map",map.toString())

            holder.image_selector.isSelected = item.isSelector

            val showDate = TimeUtils.date2FormatDate(item.dueDate)

            if (item.status != 4001) {
                holder.recycler_view_child.visibility =
                    if (item.isSelector) View.VISIBLE else View.GONE
                holder.image_child_show.visibility = View.VISIBLE
                if (holder.recycler_view_child.visibility == View.VISIBLE) {
                    holder.image_child_show.setImageResource(R.drawable.ic_loan_up)
                } else {
                    holder.image_child_show.setImageResource(R.drawable.ic_loan_down)
                }
                holder.view.visibility = if (item.isSelector) View.GONE else View.VISIBLE
                val typefaceName = Typeface.createFromAsset(mContext?.assets, "Poppins-SemiBold.ttf")
                holder.tv_title.typeface = typefaceName
                holder.tv_title.text = showDate
                holder.tv_title.setTextColor(Color.parseColor("#333333"))

                if (item.status == 3002){
                    holder.tv_title.text = "${item.overdueDays} Día(s) vencido"
                    holder.tv_title.setTextColor(Color.parseColor("#FF3737"))
                }
                holder.image_selector.setImageResource(R.drawable.selector_to_index);

                holder.tv_index.isSelected = false;
            }else{
                holder.tv_title.setText("Pagado")
                holder.tv_title.setTextColor(Color.parseColor("#00C9E5"))
                holder.recycler_view_child.visibility = View.GONE
                holder.image_child_show.visibility = View.GONE
                holder.image_selector.visibility = View.GONE

                holder.image_selector.isSelected = true
                holder.tv_index.isSelected = true
            }


            holder.recycler_view_child.layoutManager = LinearLayoutManager(mContext)
            var list: MutableList<MPayLoanChildBean> = ArrayList()

            if (map != null) {
                for (key in map.keys) {

                    var value = map[key]
//                    if (key.contains("Comisión")) {
//                        Log.e("===item.overdueDays", item.overdueDays.toString())
//                        Log.e("===item.noPenaltyDays", item.noPenaltyDays.toString())
//                        if (item.overdueDays != null && item.noPenaltyDays != null) {
//                            if (item.overdueDays.toString().toInt() <= item.noPenaltyDays.toString().toInt()) {
//                                val comision = map.get(key).toString()
//                                list.add(MPayLoanChildBean(1, "Esta Comisión por demora, puede eliminarse - $${(comision).extFormatMoney()}", "${item.noPenaltyDays}") )
//                            }
//                        }
//                    }else
                    if (key.contains("hasGracePenalty")) {
                        Log.e("===item.overdueDays", item.overdueDays.toString())
                        Log.e("===item.noPenaltyDays", item.noPenaltyDays.toString())
//                        if (item.overdueDays != null && item.noPenaltyDays != null) {
//                            if (item.overdueDays.toString().toInt() <= item.noPenaltyDays.toString().toInt()) {
//                                val comision = map.get(key).toString()
//                                list.add(MPayLoanChildBean(1, "Esta Comisión por demora, puede eliminarse - $${(comision).extFormatMoney()}", "${item.noPenaltyDays}") )
//                            }
//                        }
                        val hasGracePenalty = map.get(key).toString()
                        list.add(MPayLoanChildBean(1, hasGracePenalty, "${item.noPenaltyDays}") )
                    }else
                    if ( key.contains("Principal") || key.contains("Interés") || key.contains("Cargo por servicios(I.V.A. incluído)") || key.contains("Impuesto de Timbres y Estampillas") || key.contains("Comisión por demora") ){
                        list.add(value?.let { MPayLoanChildBean(0, key, value) }!!)
                    }
                }
            }


            var adapter = MPayLoanChildAdapter(mContext)
            adapter.datas = list;
            holder.recycler_view_child.adapter = adapter


            holder.image_child_show.setOnClickListener{
                if (holder.recycler_view_child.visibility == View.VISIBLE) {
                    holder.recycler_view_child.visibility = View.GONE
                    holder.view.visibility = View.VISIBLE
                    holder.image_child_show.setImageResource(R.drawable.ic_loan_down)
                } else {
                    holder.recycler_view_child.visibility = View.VISIBLE
                    holder.image_child_show.setImageResource(R.drawable.ic_loan_up)
                }
            }

            holder.image_selector.setOnClickListener {
                if (item.status != 4001) {
                    val isSelect = holder.image_selector.isSelected
                    if (!isSelect) {
                        itemClick?.onItemClick(it, position, true)
                    } else {
                        itemClick?.onItemClick(it, position, false)
                    }
                }
            }
        }



        var itemClick: onItemClickListener? = null

        var showClick: onItemClickListener? = null

        interface onItemClickListener {
            fun onItemClick(view: View, position: Int, isSelect: Boolean)
        }

    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var linear_name: LinearLayout = itemView.findViewById(R.id.linear_name)
        var image_selector: ImageView = itemView.findViewById(R.id.image_selector)
        var image_child_show: ImageView = itemView.findViewById(R.id.img_child_show)
        var tv_index: TextView = itemView.findViewById(R.id.tv_index);
        var tv_title: TextView = itemView.findViewById(R.id.tv_title);
        var recycler_view_child: RecyclerView = itemView.findViewById(R.id.recycler_view_child);
        var view: VerticalDashedLineView = itemView.findViewById(R.id.view);
    }

    class MPayLoanChildAdapter(context: Context?) :
        RecyclerView.Adapter<MPayLoanActivity.ChildViewHolder>() {

        var datas: MutableList<MPayLoanChildBean> = ArrayList()

        var mContext: Context? = context;
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChildViewHolder {
            val itemView: View = LayoutInflater.from(mContext)
                .inflate(R.layout.item_m_pay_loan_child, parent, false)
            return ChildViewHolder(itemView)
        }

        override fun getItemCount(): Int {
            return datas.size;
        }

        override fun onBindViewHolder(holder: ChildViewHolder, position: Int) {
            var item = datas.get(position)
            Log.e("----item.title", item.title)
            Log.e("----item.type", item.type.toString())
            Log.e("----item.name", item.name)
            holder.tv_title.setText(item.title)

            if (item.type == 1){
                holder.image_tips.visibility = View.VISIBLE
                holder.tv_title.setTextColor(Color.parseColor("#FFB003"))
                holder.tv_content.visibility = View.GONE
            }else{
                holder.image_tips.visibility = View.GONE
                holder.tv_content.visibility = View.VISIBLE
                holder.tv_content.setText("$${StringUtils.formatNumberWithCommas(item.name)}")
            }
            holder.image_tips.setOnClickListener {
                show(holder.tv_title, item)
            }
        }



        var window: PopupWindow? = null
        private fun show(linear: View, mPayLoanChildBean: MPayLoanChildBean) {
            if (window != null) {
                window!!.dismiss()
            }
            val inflate: View =
                LayoutInflater.from(linear.context).inflate(R.layout.p_payment_tips, null)
            val text_content = inflate.findViewById<TextView>(R.id.tv_content)
            text_content.text = "Si paga en los ${mPayLoanChildBean.name} primeros días desde la fecha de vencimiento, cancelaremos esta Comisión por demora, Gastos de cobranza, Gastos de telefonía ."
            window = PopupWindow(
                inflate,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true
            )
            val dw = ColorDrawable(0x00000000)
            window!!.setBackgroundDrawable(dw)
            inflate.setOnClickListener { window!!.dismiss() }
            window!!.isOutsideTouchable = true
            showUp(inflate, linear)
            window!!.update()
        }

        private fun showUp(v: View, linear: View) {
            v.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val measuredHeight = v.measuredHeight
            val location = IntArray(2)
            linear.getLocationOnScreen(location)
            window!!.showAsDropDown(linear, Gravity.NO_GRAVITY, 0, 0)
        }
    }

    class ChildViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tv_title: TextView = itemView.findViewById(R.id.tv_title)
        var tv_content: TextView = itemView.findViewById(R.id.tv_content)
        var image_tips: ImageView = itemView.findViewById(R.id.image_tips)
    }

    public override fun onStop() {
        super.onStop()
//        hideMyLoading()
    }

    override fun onDestroy() {
        super.onDestroy()
        PointMgr.sendEvent("cl_video_14_upload_yes")
        Log.e("PointMgr.INSTANCE.sendEvent", "cl_video_14_upload_yes")
    }
}